'use strict';

/**
 * Module dependencies
 */

require('dotenv').config();

const fs = require('fs');
const join = require('path').join;
const express = require('express');
const mysql = require('mysql');
const passport = require('passport');
// todo 配置文件
const config = require('./config');

const models = join(__dirname, 'app/models');
const port = process.env.PORT || 3000;
const app = express();

/**
 * Expose
 */

module.exports = app;

// Bootstrap models
fs.readdirSync(models)
	.filter(file => ~file.search(/^[^\.].*\.js$/))
	.forEach(file => require(join(models, file)));

// Bootstrap routes
require('./config/passport')(passport);
require('./config/express')(app, passport);
require('./config/routes')(app, passport);

connect()
	.on('error', console.log)
	.on('disconnected', connect)
	.once('open', listen);

function listen () {
	if (app.get('env') === 'test') return;
	app.listen(port);
	console.log('Express app started on port ' + port);
}

/**
 * todo mysql的启动链接配置
 * @return {*}
 */
function connect () {
	var options = { server: { socketOptions: { keepAlive: 1 } } };
	return mysql.connect(config.db, options).connection;
}
